package com.hxminer.hxwebs.controller;

import com.hxminer.hxwebs.enmus.ResultEnum;
import com.hxminer.hxwebs.exceptions.HxException;
import com.hxminer.hxwebs.model.Result;
import com.hxminer.hxwebs.model.UserAddress;
import com.hxminer.hxwebs.repository.AddressRespository;
import com.hxminer.hxwebs.service.AddressService;
import com.hxminer.hxwebs.utils.ResultUitl;
import jdk.nashorn.internal.runtime.UserAccessorProperty;
import org.hibernate.annotations.GeneratorType;

import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.repository.query.Param;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.slf4j.Logger;

import javax.validation.Valid;
import java.util.List;

/**
 * @Author:Charles.zhang
 * @Description
 * @Date: Created in 下午6:19 2018/5/15
 * @Modified by:
 */


@RestController
@Transactional
public class AddressControler {

    private final static Logger logger = LoggerFactory.getLogger(UserAddress.class);

    @Autowired
    private AddressRespository addressRespository;

    @Autowired
    private AddressService addressService;


    @GetMapping(value = "/address")
    public List<UserAddress> getAddressList() {

        /**
         *@Despription 查找所有用户的地址信息
         *@Params []
         *@return java.util.List<com.hxminer.hxwebs.model.UserAddress>
         *@Created Charles.Zhang
         *@Time 2018/5/15
         *@Modify
         */

        logger.info("get userAddress list");
        return addressRespository.findAll();
    }

    @PostMapping(value = "/hxminer/addressAdd")
    public Result<UserAddress> addressAdd(@Valid UserAddress userAddress, BindingResult bindingResult) {
        /**
         *@Despription 插入一个用户地址
         *@Params [userAddress, bindingResult]
         *@return com.hxminer.hxwebs.model.Result<com.hxminer.hxwebs.model.UserAddress>
         *@Created Charles.Zhang
         *@Time 2018/5/15
         *@Modify
         */
        if (bindingResult.hasErrors()) {

            //return null;
            return ResultUitl.error(1, bindingResult.getFieldError().getDefaultMessage());
        }


        UserAddress addressFind = findByUserNameAndAddress(userAddress.getUserName(), userAddress.getAddress());
        if (addressFind != null) {
            return ResultUitl.error(1, bindingResult.getFieldError().getDefaultMessage());
        }

        //userAddress.setId(userAddress.getId());
        userAddress.setUserName(userAddress.getUserName());
        userAddress.setAddress(userAddress.getAddress());
        userAddress.setCellPhone(userAddress.getCellPhone());
        userAddress.setTelPhone(userAddress.getTelPhone());
        userAddress.setReceiveName(userAddress.getReceiveName());

        System.out.println("addressAdd");

        return ResultUitl.success(addressRespository.save(userAddress));
    }

    @GetMapping(value = "/hxminer/address/userName/{userName}")
    public List<UserAddress> addressListByUserName(@PathVariable("userName") String userName) {
        /**
         *@Despription 根据用户名来查询
         *@Params [userName]
         *@return com.hxminer.hxwebs.model.Result<com.hxminer.hxwebs.model.UserAddress>
         *@Created Charles.Zhang
         *@Time 2018/5/15
         *@Modify
         */

        logger.info("根据用户名来查询" + userName);

        return addressRespository.findByUserName(userName);
    }

    @GetMapping(value = "/address/address/{address}")
    public List<UserAddress> addressListByAdddress(@PathVariable("address") String address) {
        /**
         *@Despription 根据地址来查询
         *@Params [userName]
         *@return com.hxminer.hxwebs.model.Result<com.hxminer.hxwebs.model.UserAddress>
         *@Created Charles.Zhang
         *@Time 2018/5/15
         *@Modify
         */

        return addressRespository.findByAddress(address);
    }


    @PutMapping(value = "/address/{id}")
    public UserAddress addressUpdate(@PathVariable("id") Integer id,
                                     @RequestParam("userName") String userName,
                                     @RequestParam("address") String address,
                                     @RequestParam("telPhone") String telPhone,
                                     @RequestParam("cellPhone") String cellPhone) {
        /**
         *@Despription 根据ip来更改 根据用户名来更改已经无法满足了
         *@Params [id, userName, address, telPhone, cellPhone]
         *@return com.hxminer.hxwebs.model.UserAddress
         *@Created Charles.Zhang
         *@Time 2018/5/15
         *@Modify
         */
        UserAddress userAddress = new UserAddress();
        userAddress.setId(id);
        userAddress.setUserName(userName);
        userAddress.setAddress(address);
        userAddress.setTelPhone(telPhone);
        userAddress.setCellPhone(cellPhone);

        return addressRespository.save(userAddress);
    }


    @DeleteMapping(value = "/address/{id}")
    public void addressDelete(@PathVariable("id") Integer id) {

        addressRespository.deleteById(id);

    }

    /**
     * 删除地址
     *
     * @param userAddress
     * @param bindingResult
     * @return
     */
    @PostMapping(value = "/hxminer/deleteByNameAndAddress")
    public Result<String> deleteByUserNameAndAddress(@Valid UserAddress userAddress,
                                                     BindingResult bindingResult) {

        if (bindingResult.hasErrors()) {

            //return null;
            return ResultUitl.error(1, bindingResult.getFieldError().getDefaultMessage());
            //throw new HxException(ResultEnum.DEETE_ERROR);
        }

        logger.info("deleteByNameAndAddress:  " + userAddress.getUserName() + "  " + userAddress.getAddress());
        addressRespository.deleteByUserNameAndAddress(userAddress.getUserName(), userAddress.getAddress());
        return ResultUitl.success("delete success");
    }


    @PostMapping(value = "/hxminer/findByUserNameAndAddress")
    public UserAddress findByUserNameAndAddress(@RequestParam String userName, @RequestParam String address) {

        /**
         *@Despription 根据用户名和地址查询
         *@Params [userName, address]
         *@return com.hxminer.hxwebs.model.UserAddress
         *@Created Charles.Zhang
         *@Time 2018/5/16
         *@Modify
         */

        UserAddress userAddress = addressRespository.findByUserNameAndAddress(userName, address);
        return userAddress;
    }

    @PostMapping(value = "/updateAddressByName")
    public String updateAddressByName(@RequestParam String oldName, @RequestParam String newReceiveName) {
        System.out.println(oldName + "  " + newReceiveName);
        addressRespository.updateAddressByName(oldName, newReceiveName);
        return "success";
    }


    @PostMapping(value = "/hxminer/updateAddressByNameAndAddress")
    public Result<String> updateAddressByNameAndAddress(@Valid UserAddress userAddress,
                                                        BindingResult bindingResult) {
        logger.info("updateAddressByNameAndAddress: " + userAddress.getUserName() + "  " + userAddress.getReceiveName() + "  " + userAddress.getAddress());
        //addressRespository.updateAddressByNameAndAddress(oldName,oldAddress,newReceiveName,newTelPhone,newCellPhone,newAddress);
        if (bindingResult.hasErrors()) {

            return ResultUitl.error(1, bindingResult.getFieldError().getDefaultMessage());
        }

        addressRespository.updateAddressByNameAndAddress(userAddress.getUserName(),
                userAddress.getOldAddress(),
                userAddress.getReceiveName(),
                userAddress.getTelPhone(),
                userAddress.getCellPhone(),
                userAddress.getAddress());

        return ResultUitl.success("delete success");
    }


}
